package com.goldsprite.projecttemplategenerator.test;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipExtractor {
	public static void unzip(File zipFile, String destDirectory) throws IOException {
		File destDir = new File(destDirectory);
		if (!destDir.exists()) {
			destDir.mkdirs();
		}

		try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile))) {
			ZipEntry entry;
			while ((entry = zipIn.getNextEntry()) != null) {
				String filePath = destDirectory + File.separator + entry.getName();
				if (entry.isDirectory()) {
					new File(filePath).mkdirs();
				} else {
					extractFile(zipIn, filePath);
				}
				zipIn.closeEntry();
			}
		}
	}

	private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
		try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
			byte[] buffer = new byte[4096];
			int bytesRead;
			while ((bytesRead = zipIn.read(buffer)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
		}
	}
}
